package com.example.yskjproject.service;

import static com.example.yskjproject.App.context;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;

import com.android.tu.loadingdialog.LoadingDailog;
import com.example.yskjproject.MainActivity;
import com.example.yskjproject.R;
import com.example.yskjproject.databinding.BottomDiscBinding;
import com.example.yskjproject.helper.SeriaPortHelper;
import com.example.yskjproject.model.GlobalStateManager;
import com.example.yskjproject.utils.LogUtils;
import com.example.yskjproject.utils.SerialPortUtils;
import com.example.yskjproject.view.ToastFormat;
import com.google.common.collect.Lists;
import com.yujing.utils.YConvert;
import com.yujing.yserialport.DataListener;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;

public class BottomDiscService extends Service {
    private BottomDiscBinding mBottomDiscBinding;
    private WindowManager windowManager;
    private View floatingView;
    private final Handler mAddHandler = new Handler();
    private final Handler mMinusHandler = new Handler();
    private List<String> listConstellation =
            Lists.newArrayList("标准模式", "等速模式", "弹力模式");
    private String[] listConstellation1 = new String[]{"标准模式", "等速模式", "弹力模式"};
    private int currentIndex = 0;
    private int rightCurrentIndex = 0;
    private int leftElectrical = 1;
    private int rightElectrical = 1;
    private int leftCount = 0;
    private int rightCount = 0;
    private AnimationDrawable animationDrawable;
    private boolean peopleBoolean = true;

    private String settingMode = "mode1";
    private static SeriaPortHelper seriaPortHelper;
    private LoadingDailog.Builder loadBuilder;
    private View loadingDailog;
    private int leftPosition;
    private int rightPosition;
    private int rightLeftPosition;
    private int rightRightPosition;

    private int zeroInt = 0;
    private int currentDisValue = 2;
    private int rightCurrentDisValue = 2;
    private WindowManager.LayoutParams layoutParams;
    private static ServiceCallback callback;
    private final Handler mRightAddHandler = new Handler();
    private final Handler mRightMinusHandler = new Handler();
    private final Runnable mAddInCrementRunnable = new Runnable() {
        @Override
        public void run() {
            currentDisValue = Integer.parseInt(mBottomDiscBinding.disKg.getText().toString());
            if (currentDisValue >= 100) {
                return;
            }
            currentDisValue++;
            mBottomDiscBinding.disKg.setText(String.valueOf(currentDisValue));
            mAddHandler.postDelayed(this, 100);
        }
    };
    private final Runnable mMinusInCrementRunnable = new Runnable() {
        @Override
        public void run() {
            currentDisValue = Integer.parseInt(mBottomDiscBinding.disKg.getText().toString());
            if (currentDisValue <= 2) {
                return;
            }
            currentDisValue--;
            mBottomDiscBinding.disKg.setText(String.valueOf(currentDisValue));
            mMinusHandler.postDelayed(this, 100);
        }
    };

    public static void setCallback(ServiceCallback serviceCallback) {
        callback = serviceCallback;
    }

    private final Runnable mRightAddInCrementRunnable = new Runnable() {
        @Override
        public void run() {
            rightCurrentDisValue = Integer.parseInt(mBottomDiscBinding.rightDisKg.getText().toString());
            if (rightCurrentDisValue >= 100) {
                return;
            }
            rightCurrentDisValue++;
            mBottomDiscBinding.rightDisKg.setText(String.valueOf(rightCurrentDisValue));
            mAddHandler.postDelayed(this, 100);
        }
    };
    private final Runnable mRightMinusInCrementRunnable = new Runnable() {
        @Override
        public void run() {
            rightCurrentDisValue = Integer.parseInt(mBottomDiscBinding.rightDisKg.getText().toString());
            if (rightCurrentDisValue <= 2) {
                return;
            }
            rightCurrentDisValue--;
            mBottomDiscBinding.rightDisKg.setText(String.valueOf(rightCurrentDisValue));
            mMinusHandler.postDelayed(this, 100);
        }
    };

    int heightInDp = 215; // 自定义的高度，单位为 dp
    int heightInPixels = (int) TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP, heightInDp, context.getResources().getDisplayMetrics());

    int goneLayoutHeightInDp = 100;
    int goneLayoutWidthInDp = 200;
    int goneHeightInPixels = (int) TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP, goneLayoutHeightInDp, context.getResources().getDisplayMetrics());
    int goneWidthInPixels = (int) TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP, goneLayoutWidthInDp, context.getResources().getDisplayMetrics());


    @Override
    public void onCreate() {
        super.onCreate();

        // 初始化 WindowManager
        windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        mBottomDiscBinding = BottomDiscBinding.inflate(inflater, null, false);
        floatingView = mBottomDiscBinding.getRoot();

        // 悬浮窗布局参数
        layoutParams = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.MATCH_PARENT, // 宽度
                WindowManager.LayoutParams.WRAP_CONTENT, // 高度
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ?
                        WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY : WindowManager.LayoutParams.TYPE_PHONE,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, // 确保不阻止触摸事件

                PixelFormat.TRANSLUCENT // 透明背景
        );

        layoutParams.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;

        // 添加悬浮窗
        windowManager.addView(floatingView, layoutParams);

        // 初始化控件和事件
        initView();
        showLoadingDialog(0);
    }

    private void showLoadingDialog(int leftOrRight) {
        seriaPortHelper.openSerial(true, true, "mode1", 1, "2", leftOrRight);
        // 加载自定义布局
        loadingDailog = LayoutInflater.from(getApplicationContext()).inflate(R.layout.dialog_loading, null);

        // 设置窗口参数
        WindowManager.LayoutParams params = new WindowManager.LayoutParams();
        params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY; // 设置悬浮窗类型
        params.format = PixelFormat.TRANSLUCENT;

        // 设置窗口的 flag 以禁用后面界面点击
        params.flags =   // 不接收输入事件
                WindowManager.LayoutParams.FLAG_DIM_BEHIND     // 背景变暗
                        | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH  // 防止点击穿透
        ; // 使背景区域不能接收点击事件

        // 设置背景的透明度，可以通过设置 dimAmount 来控制
        params.dimAmount = 0.6f; // 背景的暗度，范围从 0 到 1，0 表示完全透明，1 表示完全不透明

        // 设置窗口居中
        params.gravity = Gravity.CENTER;
        params.width = WindowManager.LayoutParams.WRAP_CONTENT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;

        // 将视图添加到 WindowManager 中
        windowManager.addView(loadingDailog, params);

    }

    private void removeLoadingDialog() {
        if (loadingDailog != null && windowManager != null) {
            windowManager.removeView(loadingDailog); // 从 WindowManager 中移除弹窗
            loadingDailog = null;  // 清除对弹窗的引用
            ToastFormat format = new ToastFormat(this);
            format.InitToast();
            format.setText("零点重置成功");
            format.setGravity(Gravity.CENTER);
            format.show();
            mBottomDiscBinding.startStop.setText("开始");
            mBottomDiscBinding.pauseState.setText("当前暂停中");
            settingMode = "mode1";
            leftElectrical = 1;
            rightElectrical = 1;
            zeroInt = 0;
            seriaPortHelper.openSerial(true, peopleBoolean, settingMode, zeroInt, "2", 0);
        }
    }


    private void initView() {
        seriaPortHelper = new SeriaPortHelper();
        seriaPortHelper.initSerial(this, dataListener);
        mBottomDiscBinding.openSer.setClickable(true);
        mBottomDiscBinding.openSer.setFocusable(true);
        if (callback != null) {
            callback.onServiceStarted();
        }
        mBottomDiscBinding.openSer.setOnClickListener(ser -> {
            if (mBottomDiscBinding.startStop.getVisibility() == View.VISIBLE) {
                if (mBottomDiscBinding.startStop.getText().toString().equals("开始")) {
                    switch (mBottomDiscBinding.ydMode.getText().toString()) {
                        case "基础力模式":
                            settingMode = "mode1";
                            break;
                        case "标准模式":
                            settingMode = "mode2";
                            break;
                        case "等速模式":
                            settingMode = "mode3";
                            break;
                        case "弹力模式":
                            settingMode = "mode4";
                            break;
                        case "休眠模式":
                            settingMode = "mode5";
                            break;
                    }
                    zeroInt = 0;
                    seriaPortHelper.openSerial(true, peopleBoolean, settingMode, zeroInt, mBottomDiscBinding.disKg.getText().toString().trim(), 0);
                    mBottomDiscBinding.pauseState.setText("当前正在训练中");
                    mBottomDiscBinding.startStop.setText("停止");
//                    mBottomDiscBinding.leftIvCollision.setVisibility(View.VISIBLE);
//                    mBottomDiscBinding.leftIvCollision.setBackgroundResource(R.drawable.collision_anumation);
//                    AnimationDrawable animationDrawable = (AnimationDrawable) mBottomDiscBinding.leftIvCollision.getBackground();
//                    animationDrawable.setOneShot(true);
//                    animationDrawable.start();
//
//
//
                } else {
                    settingMode = "mode1";
                    zeroInt = 0;
                    seriaPortHelper.openSerial(true, peopleBoolean, settingMode, zeroInt, "2", 0);
                    mBottomDiscBinding.startStop.setText("开始");
                    mBottomDiscBinding.pauseState.setText("当前暂停中");
                }
            } else {
                mBottomDiscBinding.rlDialLeftFunction.setVisibility(View.VISIBLE);
                mBottomDiscBinding.rlDialRightFunction.setVisibility(View.VISIBLE);
                mBottomDiscBinding.llSpeedDial.setVisibility(View.VISIBLE);
                mBottomDiscBinding.hcpView.setVisibility(View.VISIBLE);
                mBottomDiscBinding.startStop.setVisibility(View.VISIBLE);
                mBottomDiscBinding.pauseState.setVisibility(View.VISIBLE);
                mBottomDiscBinding.ivHumanBody.setVisibility(View.GONE);
            }
        });
        mBottomDiscBinding.rightOpenSer.setOnClickListener(ser -> {
            if (mBottomDiscBinding.rightStartStop.getVisibility() == View.VISIBLE) {
                if (mBottomDiscBinding.rightStartStop.getText().toString().equals("开始")) {
                    switch (mBottomDiscBinding.rightYdMode.getText().toString()) {
                        case "基础力模式":
                            settingMode = "mode1";
                            break;
                        case "标准模式":
                            settingMode = "mode2";
                            break;
                        case "等速模式":
                            settingMode = "mode3";
                            break;
                        case "弹力模式":
                            settingMode = "mode4";
                            break;
                        case "休眠模式":
                            settingMode = "mode5";
                            break;
                    }
                    ;
                    zeroInt = 0;
                    seriaPortHelper.openSerial(true, peopleBoolean, settingMode, zeroInt, mBottomDiscBinding.rightDisKg.getText().toString().trim(), 1);
                    mBottomDiscBinding.rightPauseState.setText("当前正在训练中");
                    mBottomDiscBinding.rightStartStop.setText("停止");
                } else {
                    settingMode = "mode1";
                    zeroInt = 0;
                    seriaPortHelper.openSerial(true, peopleBoolean, settingMode, zeroInt, "2", 1);
                    mBottomDiscBinding.rightStartStop.setText("开始");
                    mBottomDiscBinding.rightPauseState.setText("当前暂停中");
                }
            } else {
                mBottomDiscBinding.rightRightRlDialFunction.setVisibility(View.VISIBLE);
                mBottomDiscBinding.rightLeftRlDialFunction.setVisibility(View.VISIBLE);
                mBottomDiscBinding.llRightSpeedDial.setVisibility(View.VISIBLE);
                mBottomDiscBinding.rightHcpView.setVisibility(View.VISIBLE);
                mBottomDiscBinding.rightStartStop.setVisibility(View.VISIBLE);
                mBottomDiscBinding.rightPauseState.setVisibility(View.VISIBLE);
                mBottomDiscBinding.rightIvHumanBody.setVisibility(View.GONE);
            }
        });


        mBottomDiscBinding.onePeople.setOnClickListener(click -> {
            //更改 状态之前 先要去基础力模式
            settingMode = "mode1";
            zeroInt = 0;
            seriaPortHelper.openSerial(true, peopleBoolean, settingMode, zeroInt, "2", 0);
            if (mBottomDiscBinding.onePeople.getText().toString().equals("双人模式")) {
                mBottomDiscBinding.onePeople.setText("单人模式");
                mBottomDiscBinding.llRight.setVisibility(View.VISIBLE);
                mBottomDiscBinding.rightRlLeftDial.setVisibility(View.VISIBLE);
                mBottomDiscBinding.rightOnePeople.setText("单人模式");
                peopleBoolean = false;
            } else {
                seriaPortHelper.openSerial(true, peopleBoolean, settingMode, zeroInt, "2", 1);
                mBottomDiscBinding.onePeople.setText("双人模式");
                mBottomDiscBinding.rightRlLeftDial.setVisibility(View.GONE);
                mBottomDiscBinding.llRight.setVisibility(View.GONE);
                peopleBoolean = true;
            }
            mBottomDiscBinding.pauseState.setText("当前暂停中");
            mBottomDiscBinding.startStop.setText("开始");
            mBottomDiscBinding.rightDisKg.setText("2");
            mBottomDiscBinding.disKg.setText("2");
            mBottomDiscBinding.rightStartStop.setText("开始");
            mBottomDiscBinding.rightPauseState.setText("当前暂停中");
            mBottomDiscBinding.rightYdMode.setText("标准模式");
            mBottomDiscBinding.ydMode.setText("标准模式");

        });
        mBottomDiscBinding.rightOnePeople.setOnClickListener(click -> {
            //更改 状态之前 先要去基础力模式
            settingMode = "mode1";
            zeroInt = 0;
            seriaPortHelper.openSerial(true, peopleBoolean, settingMode, zeroInt, "2", 0);
            if (mBottomDiscBinding.rightOnePeople.getText().toString().equals("单人模式")) {
                mBottomDiscBinding.rightRlLeftDial.setVisibility(View.GONE);
                mBottomDiscBinding.llRight.setVisibility(View.GONE);
                mBottomDiscBinding.onePeople.setText("双人模式");
                peopleBoolean = true;
            }
            mBottomDiscBinding.pauseState.setText("当前暂停中");
            mBottomDiscBinding.startStop.setText("开始");
        });


        mBottomDiscBinding.rightYbDialVisible.setOnClickListener(view -> {
            mBottomDiscBinding.llRightSpeedDial.setVisibility(View.GONE);
            mBottomDiscBinding.rightRightRlDialFunction.setVisibility(View.GONE);
            mBottomDiscBinding.rightLeftRlDialFunction.setVisibility(View.GONE);
            mBottomDiscBinding.rightHcpView.setVisibility(View.GONE);
            mBottomDiscBinding.rightStartStop.setVisibility(View.GONE);
            mBottomDiscBinding.rightPauseState.setVisibility(View.GONE);
            mBottomDiscBinding.pauseState.setText("当前暂停中");
            mBottomDiscBinding.startStop.setText("开始");
            mBottomDiscBinding.rightIvHumanBody.setVisibility(View.VISIBLE);
            settingMode = "mode1";
            zeroInt = 0;
            seriaPortHelper.openSerial(true, peopleBoolean, settingMode, zeroInt, "2", 1);

        });
        mBottomDiscBinding.ybDialVisible.setOnClickListener(view -> {
            mBottomDiscBinding.rlDialLeftFunction.setVisibility(View.GONE);
            mBottomDiscBinding.rlDialRightFunction.setVisibility(View.GONE);
            mBottomDiscBinding.llSpeedDial.setVisibility(View.GONE);
            mBottomDiscBinding.hcpView.setVisibility(View.GONE);
            mBottomDiscBinding.startStop.setVisibility(View.GONE);
            mBottomDiscBinding.pauseState.setVisibility(View.GONE);
            mBottomDiscBinding.pauseState.setText("当前暂停中");
            mBottomDiscBinding.startStop.setText("开始");
            mBottomDiscBinding.ivHumanBody.setVisibility(View.VISIBLE);
            settingMode = "mode1";
            zeroInt = 0;
            seriaPortHelper.openSerial(true, peopleBoolean, settingMode, zeroInt, "2", 0);
        });

        mBottomDiscBinding.zeroN.setOnClickListener(yd -> {
            showLoadingDialog(0);
            mBottomDiscBinding.disKg.setText("2");
        });
        mBottomDiscBinding.rightZeroN.setOnClickListener(yd -> {
            showLoadingDialog(1);
            mBottomDiscBinding.rightDisKg.setText("2");
        });

        mBottomDiscBinding.ydMode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                settingMode = "mode1";
                zeroInt = 0;
                seriaPortHelper.openSerial(true, peopleBoolean, settingMode, zeroInt, "2", 0);
                currentIndex = (currentIndex + 1) % listConstellation1.length;
                mBottomDiscBinding.ydMode.setText(listConstellation1[currentIndex]);
                mBottomDiscBinding.pauseState.setText("当前暂停中");
                mBottomDiscBinding.startStop.setText("开始");
            }
        });

        mBottomDiscBinding.rightYdMode.setOnClickListener(view -> {
                    mBottomDiscBinding.rightPauseState.setText("当前暂停中");
                    mBottomDiscBinding.rightStartStop.setText("开始");
                    settingMode = "mode1";
                    zeroInt = 0;
                    seriaPortHelper.openSerial(true, peopleBoolean, settingMode, zeroInt, "2", 1);
                    rightCurrentIndex = (rightCurrentIndex + 1) % listConstellation1.length;
                    mBottomDiscBinding.rightYdMode.setText(listConstellation1[rightCurrentIndex]);
                    switch (mBottomDiscBinding.rightYdMode.getText().toString()) {
                        case "基础力模式":
                            settingMode = "mode1";
                            break;
                        case "标准模式":
                            settingMode = "mode2";
                            break;
                        case "等速模式":
                            settingMode = "mode3";
                            break;
                        case "弹力模式":
                            settingMode = "mode4";
                            break;
                        case "休眠模式":
                            settingMode = "mode5";
                            break;
                    }
                }
        );
        mBottomDiscBinding.add.setOnClickListener(add -> {
            Integer addInteger = Integer.valueOf(mBottomDiscBinding.disKg.getText().toString().trim());
            if (addInteger == 100) {
                return;
            }
            int nextInteger = addInteger + 1;
            mBottomDiscBinding.disKg.setText(String.valueOf(nextInteger));
            settingMode = "mode2";
            zeroInt = 0;
            if (mBottomDiscBinding.startStop.getText().equals("停止")) {
                seriaPortHelper.openSerial(true, peopleBoolean, settingMode, zeroInt, mBottomDiscBinding.disKg.getText().toString().trim(), 0);
            }
        });
        mBottomDiscBinding.rightAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Integer addInteger = Integer.valueOf(mBottomDiscBinding.rightDisKg.getText().toString().trim());
                if (addInteger == 100) {
                    return;
                }
                int nextInteger = addInteger + 1;
                mBottomDiscBinding.rightDisKg.setText(String.valueOf(nextInteger));
                settingMode = "mode2";
                zeroInt = 0;
                if (mBottomDiscBinding.rightStartStop.getText().equals("停止")) {
                    seriaPortHelper.openSerial(true, peopleBoolean, settingMode, zeroInt, mBottomDiscBinding.rightDisKg.getText().toString().trim(), 1);
                }
            }
        });

        mBottomDiscBinding.add.setOnLongClickListener(view -> {
            mAddHandler.post(mAddInCrementRunnable);
            return true;
        });
        mBottomDiscBinding.rightAdd.setOnLongClickListener(view -> {
            mRightAddHandler.post(mRightAddInCrementRunnable);
            return true;
        });

        mBottomDiscBinding.minus.setOnLongClickListener(view -> {
            mMinusHandler.post(mMinusInCrementRunnable);
            return true;
        });
        mBottomDiscBinding.rightMinus.setOnLongClickListener(view -> {
            mRightMinusHandler.post(mRightMinusInCrementRunnable);
            return true;
        });

        mBottomDiscBinding.add.setOnTouchListener((view, motionEvent) -> {
            if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                mAddHandler.removeCallbacks(mAddInCrementRunnable);
                if (mBottomDiscBinding.startStop.getText().equals("停止")) {
                    seriaPortHelper.openSerial(true, peopleBoolean, settingMode, zeroInt, mBottomDiscBinding.disKg.getText().toString().trim(), 0);
                }
            }
            return false;
        });
        mBottomDiscBinding.rightAdd.setOnTouchListener((view, motionEvent) -> {
            if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                mRightAddHandler.removeCallbacks(mRightAddInCrementRunnable);
                if (mBottomDiscBinding.startStop.getText().equals("停止")) {
                    seriaPortHelper.openSerial(true, peopleBoolean, settingMode, zeroInt, mBottomDiscBinding.rightDisKg.getText().toString().trim(), 1);
                }

            }
            return false;
        });
        mBottomDiscBinding.minus.setOnTouchListener((view, motionEvent) -> {
            if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                mMinusHandler.removeCallbacks(mMinusInCrementRunnable);
                if (mBottomDiscBinding.startStop.getText().equals("停止")) {
                    seriaPortHelper.openSerial(true, peopleBoolean, settingMode, zeroInt, mBottomDiscBinding.disKg.getText().toString().trim(), 0);
                }

            }
            return false;
        });
        mBottomDiscBinding.rightMinus.setOnTouchListener((view, motionEvent) -> {
            if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                mRightMinusHandler.removeCallbacks(mRightMinusInCrementRunnable);
                if (mBottomDiscBinding.startStop.getText().equals("停止")) {
                    seriaPortHelper.openSerial(true, peopleBoolean, settingMode, zeroInt, mBottomDiscBinding.rightDisKg.getText().toString().trim(), 1);
                }
            }
            return false;
        });

        mBottomDiscBinding.minus.setOnClickListener(minus -> {
            Integer minusInteger = Integer.valueOf(mBottomDiscBinding.disKg.getText().toString().trim());
            if (minusInteger == 2) {
                return;
            }
            int nextInteger = minusInteger - 1;
            mBottomDiscBinding.disKg.setText(String.valueOf(nextInteger));
            settingMode = "mode2";
            zeroInt = 0;
            if (mBottomDiscBinding.startStop.getText().equals("停止")) {
                seriaPortHelper.openSerial(true, peopleBoolean, settingMode, zeroInt, mBottomDiscBinding.disKg.getText().toString().trim(), 0);
            }
        });
        mBottomDiscBinding.rightMinus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Integer minusInteger = Integer.valueOf(mBottomDiscBinding.rightDisKg.getText().toString().trim());
                if (minusInteger == 2) {
                    return;
                }
                int nextInteger = minusInteger - 1;
                mBottomDiscBinding.rightDisKg.setText(String.valueOf(nextInteger));
                zeroInt = 0;
                settingMode = "mode2";
                if (mBottomDiscBinding.rightStartStop.getText().equals("停止")) {
                    seriaPortHelper.openSerial(true, peopleBoolean, settingMode, zeroInt, mBottomDiscBinding.rightDisKg.getText().toString().trim(), 1);
                }
            }
        });
        mBottomDiscBinding.rlLeftDial.setOnTouchListener((view, motionEvent) -> {
            switch (motionEvent.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    // 消费点击事件
                    return true;
            }
            return false;
        });

        mBottomDiscBinding.rightRlLeftDial.setOnTouchListener((view, motionEvent) -> {
            switch (motionEvent.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    // 消费点击事件
                    return true;
            }
            return false;
        });
    }

    /*
       监听
    */
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("[HH:mm:ss.SSS]", Locale.getDefault());
    DataListener dataListener = (hexString, bytes) -> {
        //显示
//        ToastUtil.toastShortMessage("HEX " + simpleDateFormat.format(new Date()) + "：" + YConvert.bytesToHexString(bytes));
//        com.example.yskjproject.utils.Log.e("USBSerialHelper:::::", "Received data: " + simpleDateFormat.format(new Date()) + "：" + YConvert.bytesToHexString(bytes));
        SerialPortUtils serialPortUtils = new SerialPortUtils();
        Map<String, String> serialMap = serialPortUtils.receiveSerialMsg(YConvert.bytesToHexString(bytes));
        if (serialMap != null) {
            if (serialMap.get("ZERO_POINT") == null || serialMap.get("POSITION") == null || serialMap.get("FAULT") == null || serialMap.get("RELEASE_FORCE") == null) {
                return;
            }
            String zeroCombination = String.valueOf(serialMap.get("ZERO_COMBINATION"));
            String frameHeader = String.valueOf(serialMap.get("FRAME_HEADER"));
            int zeroPoint = Integer.parseInt(serialMap.get("ZERO_POINT"));
            int position = Integer.parseInt(serialMap.get("POSITION"));
            int fault = Integer.parseInt(serialMap.get("FAULT"));
            int releaseForce = Integer.parseInt(serialMap.get("RELEASE_FORCE"));
            LogUtils.d("MainActivity " + " zeroCombination " + zeroCombination);

            if (zeroCombination.contains("55AA")) {
                rightCount++;
            } else if (zeroCombination.contains("65AA")) {
                leftCount++;
            }
            if (zeroCombination.equals("55AA1")) {
                rightElectrical = 1;
            } else if (zeroCombination.equals("65AA1")) {
                leftElectrical = 1;
            }
            if (zeroCombination.equals("55AA0")) {
                rightElectrical = 0;
            } else if (zeroCombination.equals("65AA0")) {
                leftElectrical = 0;
            }
            if (rightCount > 5 || leftCount > 5) {
                LogUtils.d("MainActivity " + " leftCount " + leftCount + " rightCount " + rightCount);
                if (rightCount == 0 || leftCount == 0) {
                    ToastFormat format = new ToastFormat(this);
                    format.InitToast();
                    format.setText("通信异常");
                    format.setGravity(Gravity.CENTER);
                    format.show();
                    settingMode = "mode1";
                    zeroInt = 0;
                    seriaPortHelper.openSerial(true, peopleBoolean, settingMode, zeroInt, "2", 0);
                    seriaPortHelper.openSerial(true, peopleBoolean, settingMode, zeroInt, "2", 1);
                    rightCount = 0;
                    leftCount = 0;
                } else {
                    leftCount = 0;
                    rightCount = 0;
                }
            }
            LogUtils.d("MainActivity " + " leftElectrical " + leftElectrical + " rightElectrical " + rightElectrical);
            if (rightElectrical == 0 && leftElectrical == 0) {
                removeLoadingDialog();
            }
            if (mBottomDiscBinding.onePeople.getText().equals("双人模式")) {
                if (animationDrawable != null && animationDrawable.isRunning()) {
                    animationDrawable.stop();
                }
                animationDrawable = null;
                if (frameHeader.equals("55AA")) {
                    if (position >= 500) {
                        mBottomDiscBinding.hcpView.setRightProgress(100);
                        rightPosition = 100;
                        GlobalStateManager.getInstance().setRightPosition(rightPosition);
                    } else {
                        mBottomDiscBinding.hcpView.setRightProgress(position / 5);
                        rightPosition = position / 5;
                        GlobalStateManager.getInstance().setRightPosition(rightPosition);
                    }
                } else {
                    if (position >= 500) {
                        mBottomDiscBinding.hcpView.setLeftProgress(100);
                        leftPosition = 100;
                        GlobalStateManager.getInstance().setRightPosition(leftPosition);
                    } else {
                        mBottomDiscBinding.hcpView.setLeftProgress(position / 5);
                        leftPosition = position / 5;
                        GlobalStateManager.getInstance().setRightPosition(leftPosition);
                    }
                }
            } else {
                if (animationDrawable != null && animationDrawable.isRunning()) {
                    animationDrawable.stop();
                }
                animationDrawable = null;
                if (frameHeader.equals("55AA")) {
                    if (position >= 500) {
                        mBottomDiscBinding.rightIvCollision.setVisibility(View.VISIBLE);
                        mBottomDiscBinding.rightHcpView.setRightProgress(100);
                        mBottomDiscBinding.rightHcpView.setLeftProgress(100);
                        rightLeftPosition = 100;
                        rightRightPosition = 100;
                        GlobalStateManager.getInstance().setRightPosition(rightRightPosition);
                        mBottomDiscBinding.rightIvCollision.setBackgroundResource(R.drawable.collision_anumation);
                        animationDrawable = (AnimationDrawable) mBottomDiscBinding.rightIvCollision.getBackground();
                        animationDrawable.setOneShot(true);
                        animationDrawable.start();
                        final int frameCount = animationDrawable.getNumberOfFrames();
                        final Runnable onAnimationEndRunnable = new Runnable() {
                            @Override
                            public void run() {
                                mBottomDiscBinding.rightIvCollision.setVisibility(View.GONE);
                            }
                        };
                        mBottomDiscBinding.rightIvCollision.postDelayed(onAnimationEndRunnable, frameCount * 100L);
                    } else {
                        mBottomDiscBinding.rightHcpView.setRightProgress(position / 5);
                        mBottomDiscBinding.rightHcpView.setLeftProgress(position / 5);
                        rightLeftPosition = position / 5;
                        rightRightPosition = position / 5;
                        GlobalStateManager.getInstance().setRightPosition(rightLeftPosition);
                    }
                } else {
                    if (position >= 500) {
                        mBottomDiscBinding.leftIvCollision.setVisibility(View.VISIBLE);
                        mBottomDiscBinding.hcpView.setRightProgress(100);
                        mBottomDiscBinding.hcpView.setLeftProgress(100);
                        leftPosition = 100;
                        rightPosition = 100;
                        GlobalStateManager.getInstance().setRightPosition(leftPosition);
                        mBottomDiscBinding.leftIvCollision.setBackgroundResource(R.drawable.collision_anumation);
                        animationDrawable = (AnimationDrawable) mBottomDiscBinding.leftIvCollision.getBackground();
                        animationDrawable.setOneShot(true);
                        animationDrawable.start();
                        final int frameCount = animationDrawable.getNumberOfFrames();
                        final Runnable onAnimationEndRunnable = new Runnable() {
                            @Override
                            public void run() {
                                mBottomDiscBinding.leftIvCollision.setVisibility(View.GONE);
                            }
                        };
                        mBottomDiscBinding.leftIvCollision.postDelayed(onAnimationEndRunnable, frameCount * 100L);
                    } else {
                        mBottomDiscBinding.hcpView.setRightProgress(position / 5);
                        mBottomDiscBinding.hcpView.setLeftProgress(position / 5);
                        leftPosition = position / 5;
                        rightPosition = position / 5;
                        GlobalStateManager.getInstance().setRightPosition(leftPosition);
                    }
                }


            }
            if (fault != 0) {
                //点击故障 弹窗
                mBottomDiscBinding.pauseState.setText("当前暂停中");
                mBottomDiscBinding.startStop.setText("开始");
                ToastFormat format = new ToastFormat(this);
                format.InitToast();
                format.setGravity(Gravity.CENTER);
                format.setText("电机故障，故障码为：" + fault);
                format.show();
                seriaPortHelper.closeSerial();

            }
            if (releaseForce == 1) {
                LogUtils.d("MainActivity" + "触发泄力保护");

                //点击弹力 弹窗
                ToastFormat format = new ToastFormat(this);
                format.InitToast();
                format.setText("安全保护，已泄力：" + fault);
                format.show();
                settingMode = "mode1";
                seriaPortHelper.openSerial(true, peopleBoolean, settingMode, zeroPoint, "2", 0);
                mBottomDiscBinding.startStop.setText("开始");
                mBottomDiscBinding.pauseState.setText("当前暂停中");
            }

        }
    };

    public static SeriaPortHelper getSeriaPortHelper() {
        return seriaPortHelper;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 销毁悬浮窗时移除布局
        if (floatingView != null) {
            windowManager.removeView(floatingView);
            removeLoadingDialog();
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public interface ServiceCallback {
        void onServiceStarted();
    }
}
